package com.aneliya.validator.suite;

import java.util.ArrayList;
import java.util.EventObject;
import java.util.Hashtable;

import com.aneliya.validator.Validator;
import com.aneliya.validator.ValidatorListener;

public class ValidationSuite extends Validator {
	protected ArrayList<Validator> validationItems;
	protected Hashtable<Validator, ValidatorListener> validationItemsListeners;
	protected Boolean valid = false;
	
	public Boolean isValid() {
		return valid;
	}
	
	public ValidationSuite() {
		super();
		validationItems = new ArrayList<Validator>();
		validationItemsListeners = new Hashtable<Validator, ValidatorListener>();
	}
	
	public void addValidationItem(Validator item) throws Exception {
		if (!validationItems.contains(item)) {
			validationItems.add(item);
			initializeValidationItemListener(item);
			
			checkValidationSuite();
		} else {
			throw new Exception("This validation item is already added!");
		}
	}

	public void removeValidationItem(Validator item) throws Exception {
		if (validationItems.contains(item)) {
			ValidatorListener listener = validationItemsListeners.get(item);
			item.removeValidatorListener(listener);
			validationItems.remove(item);
			
			checkValidationSuite();
		} else {
			throw new Exception("There is no such validation item!");
		}
	}
	
	protected void initializeValidationItemListener(Validator item) {
		ValidatorListener listener = new ValidatorListener() {
			public void validatorChanged(EventObject e) {
				checkValidationSuite();
			}
		};
		item.addValidatorListener(listener);
		validationItemsListeners.put(item, listener);
	}
	
	protected void checkValidationSuite() {
		Boolean newValid = true;
		for (Validator item : validationItems) {
			if (!item.isValid()) {
				newValid = false;
				break;
			}
		}
		
		if (newValid != valid) {
			valid = newValid;
			dispatchValidatorChanged();
		}
	} 
	
}
